<template>
  <div class="AddOrUpdate_main add_container tenantMenu_main main_container user_container">
    <div v-loading="loading" class="main_main">
      <div class="main_main_container">
        <!-- <div class="main_main_left">
          <div class="title">物料分类</div>
          <div class="main_main_left_top">
            <el-tree
              :data="typeList"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              :props="defaultProps"
              @node-click="getMaterialInfo"
            />
          </div>
        </div> -->
        <div class="main_main_right">
          <div class="SearchBar_main main_main_search">
            <!-- <div class="main_main_search_item">
              <div class="formItem_header">
                <div class="formItem_header_operate">
                  <a class="formItem_header_operate_items" @click="add">
                    <svg-icon icon-class="新增" />
                    <div class="item_name">新增</div>
                  </a>
                </div>
              </div>
            </div> -->
            <div class="main_main_search_item">
              <el-input v-model="pageData.searchValue" class="search_input" placeholder="请输入订单号或物料编码" clearable @keyup.enter.native="()=>{pageData.pageNum=1; getList()}" @clear="getList" />
              <el-button class="button_icon" icon="el-icon-search" @click.stop="()=>{pageData.pageNum=1; getList()}" />
            </div>
          </div>
          <div ref="table_container" style="margin-top:20px" class="table_container">
            <el-table
              ref="table"
              :data="tableData"
              stripe
              border
              :height="tableHeight"
              style="width: 99.9%"
              row-key="saleOrderDetailId"
              :row-class-name="rowClassName"
              :header-cell-class-name="headerCellClassName"
              @row-click="rowClick"
              @sort-change="
                (column) => {
                  sortChange(column, this);
                }
              "
              @selection-change="
                (val) => {
                  selectionChange(val, this);
                }
              "
            >
              <el-table-column type="selection" width="70" align="center" />
              <Column
                v-for="(column, index) in defaultTableColumns"
                :key="index"
                :prop="column.prop"
                :is-show="column.isShow"
                :label="column.label"
                :sortable="column.sortable"
                :min-width="column.minWidth"
                :width="column.width"
              />
              <el-table-column label="计划数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="planNumber">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.planNumber" placeholder="请输入" clearable @blur="changeList(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- <div class="addtype-main_bottoms">
            <pagination
              :total="total"
              :page.sync="pageData.pageNum"
              :limit.sync="pageData.pageSize"
              :selected-num="selectionsAll&&selectionsAll.length"
              @pagination="getList"
            />
          </div> -->
        </div>
      </div>
    </div>
    <div style="background:white;border-top:1px solid #ECECEC;" class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getMaterialType } from '@/api/saleManage/saleOrder'
// import AddOrUpdate from '../../warehouseManagement/materialInfo/addOrUpdate' // 新增或编辑页面
import { listForPlanProduction } from '@/api/saleManage/saleOrder'

import { materialList2 } from '@/api/planManagement/planProductionOrder'
export default {
  props: {
    layerid: {},
    selectedRow: {},
    saleOrderIds: {},
    planProductionId: {}
  },
  data() {
    return {
      materialTypeId: '',
      typeList: [],
      activeNum: 1,
      deptData: [],
      currentDeptId: '',
      currentDeptName: '',
      loading: false,
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        searchValue: ''
      },
      total: 1, // 数据一共有多少条
      mainId: 'saleOrderDetailId', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      peopleList: [],
      defaultTableColumns: [
        // 表格常规字段（初始值）
        { prop: 'saleOrderCode', label: '销售订单', minWidth: '120' },
        { prop: 'orderNumber', label: '订单数量', minWidth: '100' },
        { prop: 'saleCustomerDeliveryTime', label: '客户交期', minWidth: '140' },
        { prop: 'materialInventory', label: '库存数量', minWidth: '100' },
        { prop: 'willDeliverNumber', label: '未发数量', minWidth: '100' },
        { prop: 'materialCode', label: '物料编码', minWidth: '140' },
        { prop: 'materialName', label: '物料名称', minWidth: '140' },
        { prop: 'materialModel', label: '规格型号', minWidth: '140' },
        { prop: 'materialUnitName', label: '物料单位', minWidth: '80' }
      ],

      operationData: [
        // 右上角的操作按钮
        { label: '导入', perm: 'system:user:import' },
        { label: '新增', perm: 'system:user:add' },
        { label: '批量删除', perm: 'system:user:delete' },
        { label: '批量导出', perm: 'system:user:export' },
        { label: '页面配置', perm: '' }
      ],
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  mounted() {
    this.getMaterialTypeList()
    this.getList()
    this.selectionsAll = this.selectedRow
    console.log(this.selectionsAll, '初始数据')
    this.$nextTick(() => {
      this.tableHeight = this.$refs.table_container.offsetHeight
    })
  },
  methods: {
    rowClick(row, column) {
      if ((!column) || (column && (column.property === 'planNumber')) || row.isStatus) {
        console.log(1)
      } else {
        this.$refs.table.toggleRowSelection(row)
      }
    },
    headerCellClassName(data) {
      if (['planNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    rowClassName({ row, rowIndex }) {
      if (this.selectionsAll.length > 0 && ((this.selectionsAll.some(item => item.saleOrderDetailId == row.id)))) {
        return 'rowSelected'
      }
    },
    changeList(row) {
      this.selectionsAll.map((item) => {
        if (item.saleOrderDetailId == row.id) {
          item.planNumber = row.planNumber
        }
      })
    },
    getList() {
      if (this.saleOrderIds) {
        listForPlanProduction({ ...this.pageData, searchValue: this.pageData.searchValue, saleOrderIds: this.saleOrderIds, planProductionId: this.planProductionId }).then(res => {
          // res.data.forEach(ele => {
          //   ele.materialId = ele.id
          // })

          // 计划数量回显
          res.data.unMerge.map((item) => {
            item.saleOrderDetailId = item.id

            // 显示默认工艺版本号
            if (!item.engineeringRequirementId) {
              item.technologyVersionList = []
            } else {
              item.technologyVersionList = [{
                engineeringRequirementId: item.engineeringRequirementId,
                engineeringRequirementVersionCode: item.engineeringRequirementVersionCode
              }]
            }
            this.selectionsAll.map((ele) => {
              if (ele.saleOrderDetailId == item.id) {
                item.planNumber = ele.planNumber
              }
            })
          })
          this.tableData = res.data.unMerge
          this.total = res.data.unMerge.length

          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中
          })
        })
      } else {
        materialList2({ ...this.pageData, searchValue: this.pageData.searchValue }).then(res => {
          res.data.map(item => {
            // item.materialInventory = item.stockNum
            item.saleOrderDetailId = item.id
            item.materialId = item.id
            item.orderNumber = ''
            // 显示默认工艺版本号
            if (!item.engineeringRequirementId) {
              item.technologyVersionList = []
            } else {
              item.technologyVersionList = [{
                engineeringRequirementId: item.engineeringRequirementId,
                engineeringRequirementVersionCode: item.engineeringRequirementVersionCode
              }]
            }
            this.selectionsAll.map((ele) => {
              if (ele.saleOrderDetailId == item.id) {
                item.planNumber = ele.planNumber
              }
            })
          })
          this.tableData = res.data
          console.log(this.tableData, '表格数据')
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中
          })
        })
      }
    },
    getMaterialTypeList() {
      getMaterialType(this.pageData).then(res => {
        this.typeList.push({ name: '全部', id: '', children: [] })
        this.typeList[0].children = res.data
      })
    },
    // getList() {
    //   getMaterial({ ...this.pageData, materialTypeId: this.materialTypeId }).then(res => {
    //     res.data.forEach(ele => {
    //       ele.materialId = ele.id
    //     })
    //     this.tableData = res.data
    //     this.total = res.total
    //     this.$nextTick(() => {
    //       this.setSelectRow(this)// 设置行选中
    //     })
    //   })
    // },
    getMaterialInfo(item) {
      this.materialTypeId = item.id
      this.getList()
    },
    cancel() {
      this.$layer.close(this.layerid)
    },
    // // 合并数据
    // sumArr() {
    //   console.log(this.selectionsAll)
    //   // 转化为时间戳
    //   this.selectionsAll.forEach((a) => {
    //     a.saleCustomerDeliveryTimeNumber = Date.parse(a.saleCustomerDeliveryTime.replace(/\-/g, '/'))
    //   })
    //   const nameArr = [...new Set(this.selectionsAll.map(i => i.materialId))]// 名称集合
    //   const list = []
    //   nameArr.forEach(v => {
    //     const filterlist = this.selectionsAll.filter(a => v == a.materialId)
    //     list.push(filterlist)
    //   })
    //   const outArr = []
    //   // 时间戳转化
    //   list.forEach((ele) => {
    //     if (ele.length > 1) {
    //       ele[0].saleOrderDetailIds = ele.map(item => item.id).join(',')
    //       var min = Math.min.apply(Math, ele.map(o => o.saleCustomerDeliveryTimeNumber))
    //       ele[0].saleCustomerDeliveryTime = new Date(min).toLocaleDateString().slice().replace(/\//g, '-')
    //     }
    //     ele[0].planDealTime = ele[0].saleCustomerDeliveryTime
    //   })
    //   console.log(list)
    //   list.forEach((item, index) => {
    //     const moneyAdd = item.reduce((total, g) => {
    //       return total + Number(g.willDeliverNumber)
    //     }, 0)
    //     outArr.push({
    //       ...item[0],
    //       willDeliverNumber: moneyAdd
    //     })
    //   })
    //   return outArr
    // },
    onSubmit() {
      console.log(this.selectionsAll)
      if (this.selectionsAll.filter(item => !item.planNumber).length > 0) {
        this.$message.warning('计划数量不能为空')
        return
      } else if (this.selectionsAll.filter(item => item.planNumber && !this.SETTINGS.reg_no_zero.test(item.planNumber)).length > 0) {
        this.$message.warning('计划数量未正确填写')
        return
      }
      // console.log(this.selectionsAll)
      this.$parent.showMaterial(this.selectionsAll)
      this.$layer.close(this.layerid)
    }
  }
}
</script>

<style lang="less" scoped>
.main_main {
  margin:0 !important ;
  height: calc(100% - 50px);
}
.main_main_container {
  width: 100%;
  height: 100%;
  display: flex;

  .main_main_left {
    width: 250px;
    height: calc(100% - 20px);
    padding-right: 20px;
    .title {
      padding: 10px 0;
      border-bottom: 1px solid #387BFC;
      margin-bottom: 10px;
    }
    .main_main_left_top {
      width: 100%;
      height: calc(100% - 80px);
      overflow-y: auto;
      .el-tree {
        background-color: transparent;
      }
      /deep/ .el-tree-node__content:hover {
        background-color: rgba(56, 123, 252, 0.5) !important;
        color: white;
      }
    }
    .main_main_left_bottom {
      width: 100%;
      .main_main_left_bottom_item {
        background-color: rgba(74, 77, 82, 0.2);
        height: 40px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 24px;
      }
      .main_main_left_bottom_item:last-child {
        border-top: 1px solid white;
      }
      .main_main_left_bottom_item:hover {
        background-color: rgba(56, 123, 252, 0.5);
        color: white;
      }
      .active {
        .main_main_left_bottom_item {
          background-color: rgba(56, 123, 252, 1);
          color: white;
        }
      }
    }
  }
  .main_main_right {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    // border-left: 1px solid #ECECEC;

  }
}
.button{
    width: 100px;
    height: 30px;
    color: #fff;
    background-color: #387bfc;
    border-radius: 4px;
    text-align: center;
    line-height: 30px;
}
.formItem_header{
  justify-content: flex-start !important;
  align-items: flex-start !important;
  height: 40px !important;
}
.formItem_header_operate_items{
  height: 30px;
  display: flex;justify-content: center;align-items: center;
  padding: 0px 10px;font-size: 16px;border-radius: 4px;
  color: rgba(56, 123, 252, 1);background-color: rgba(235, 242, 255, 1);
  .item_name{
    font-size: 14px;padding-left: 10px;
  }
}
.formItem_header_operate_items:hover{
  background-color: rgba(235, 242, 255, 0.5);
}
.table_container{
  margin-top: 20px !important;
}
.addtype-main_bottoms{
  padding-right: 20px !important;
  margin: 10px 0;
}
.main_search_item{
  padding-right: 20px !important;
}
.main_main_search{
  padding-right: 20px !important;
}
.main_main_search_item{
  padding-left: 0px !important;
}
.main_main{
  margin-right:0 !important;
  padding-top:0 !important;
}
.button_icon{
 background:#387bfc;
 width:30px;
}
.search_input{
  width:200px;
  margin-right:10px
}
</style>
